package com.card.util;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import net.sf.json.JSONObject;

/**
 * @author jq
 * @time 2016年1月21日 下午2:47:42
 */
public class WXShareUtils {

	public static Map<String, String> sign(String url) throws Exception {
		String jsapi_ticket=getJsTicket();
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

	/**
	 * 获取jsticket
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static String getJsTicket() throws Exception {
		Properties properties = new Properties();
		String jsapi_ticket="";
		properties.load(WXShareUtils.class.getClassLoader()
				.getResourceAsStream("wx.properties"));
		long time=Long.parseLong(properties.getProperty("wx.expire_time"));
		System.out.println(properties.getProperty("wx.jsapi_ticket"));
		if(time < (new Date().getTime()/1000)){
			String appid = properties.getProperty("wx.appid");
			String appsecret = properties.getProperty("wx.appsecret");
			String token= getAccess_Token(appid, appsecret);
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
					+ token + "&type=jsapi";
			String result=HttpsUtil.get(url);
			System.out.println(result);
			jsapi_ticket=JSONObject.fromObject(result).getString("ticket");
			properties.setProperty("wx.expire_time",Long.toString(new Date().getTime()/1000+7000));
			properties.setProperty("wx.jsapi_ticket", jsapi_ticket);
			OutputStream fos=new FileOutputStream(WXShareUtils.class.getResource("/wx.properties").getPath());
			DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			properties.store(fos,df.format(new Date()));
		}else{
			jsapi_ticket=properties.getProperty("wx.jsapi_ticket");
		}
		return jsapi_ticket;
	}

	/**
	 * @author jq
	 * @time 2016年1月22日  下午5:11:26
	 * @return
	 * @throws Exception
	 */
	public static String getAccess_Token(String appid,String appsecret) throws Exception{
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ appid + "&secret=" + appsecret;
		String result = HttpsUtil.get(url);
		String access_token=JSONObject.fromObject(result).getString("access_token");
		return access_token;
	}


	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	public static void main(String[] args) throws Exception{
		System.out.println(getJsTicket());
	}
}
